package com.shhic.hhplt.server.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.shhic.hhplt.server.model.Param;
import com.shhic.hhplt.server.model.SerialCode;
import com.shhic.hhplt.server.mapper.ICodePersistDao;
import com.shhic.hhplt.server.service.ICodePersistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@DS("hhpltSys")
@Transactional
public class CodePersistServiceImpl implements ICodePersistService {


    @Autowired
    private ICodePersistDao cpDao;
    private Map<String,Object> serialCodeLockMap = new HashMap<String, Object>();

    private Object getSerialCodeLock(String codeName){
        synchronized(serialCodeLockMap){
            if(!serialCodeLockMap.containsKey(codeName)){
                serialCodeLockMap.put(codeName, new Object());
            }
            return serialCodeLockMap.get(codeName);
        }
    }


    @Override
    public String getParam(String key) {
        return cpDao.getParam(key);
    }

    @Override
    public List<Param> getAllParam() {
        return cpDao.getAllParam();
    }

    @Override
    public void deleteParam(String key) {
        cpDao.deleteParam(key);
    }

    @Override
    public void insertParam(Param param) {
        cpDao.insertParam(param);
    }

    @Override
    public void deleteSerialCode(String codeName) {
        cpDao.deleteSerialCode(codeName);
    }

    @Override
    public void insertOrUpdateSerialCode(SerialCode sc) {
        synchronized(getSerialCodeLock(sc.getCodeName())){
            SerialCode oldSc = cpDao.getSerialCode(sc.getCodeName());
            if(oldSc == null){
                cpDao.insertSerialCode(sc);
            }else{
                cpDao.updateSerialCode(sc);
            }
        }
        if(sc.isAvailable()){
            //如果是启用状态，则停用其他的
            cpDao.disableOtherSerialCodeWithSameName(sc.getCodeName());
        }
    }

    @Override
    public List<SerialCode> getAllSerialCode() {
        return cpDao.getAllSerialCode();
    }

    @Override
    public void updateNowSerialCode(String codeName, String nowCode) {
        synchronized(getSerialCodeLock(codeName)){
            cpDao.updateNowSerialCode(codeName,nowCode);
        }
    }

    @Override
    public void addRetrivedCode(String codeName, String code) {
        synchronized(getSerialCodeLock(codeName)){
            cpDao.insertRetrievedSerialCode(codeName,code);
        }
    }

    @Override
    public boolean removeIfExistRetrievedCode(String codeName, String code) {
        synchronized(getSerialCodeLock(codeName)){
            return cpDao.deleteRetrievedSerialCode(codeName,code)!= 0;
        }
    }
}
